package com.carl.app.base;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.carl.app.R;
import com.carl.app.utils.ActivityUtils;
import com.carl.app.utils.PermissionListener;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.rxbus2.RxBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * 底部 Tab 的基础 Activity
 * 继承此 Activity 后，初始化布局、添加 addItem、initialise 两个方法，传入相关的图标及文字即可。
 * 想要更换 BottomNavigationBar 风格样式，请设置 setNavBarStyle 方法。
 */

public abstract class BaseTabBottomActivity extends AppCompatActivity implements BottomNavigationBar.OnTabSelectedListener {

    private Unbinder unbinder;
    private static PermissionListener mPermissionListener;
    private static final int CODE_REQUEST_PERMISSION = 1;


    private BottomNavigationBar mBottomNavigationBar;
    private final List<Fragment> fragmentList = new ArrayList<>();
    /**
     * BottomNavigationBar 的风格，默认：MODE_DEFAULT
     */
    private int mMode = BottomNavigationBar.MODE_DEFAULT;
    /**
     * BottomNavigationBar 的背景样式，默认：BACKGROUND_STYLE_DEFAULT
     */
    private int mBackgroundStyle = BottomNavigationBar.BACKGROUND_STYLE_DEFAULT;


    protected ImmersionBar mImmersionBar;
    private InputMethodManager imm;

    protected void initImmersionBar() {
        //在BaseActivity里初始化
        mImmersionBar = ImmersionBar.with(this);
        mImmersionBar.init();
    }


    /**
     * 是否可以使用沉浸式
     * Is immersion bar enabled boolean.
     *
     * @return the boolean
     */
    protected abstract boolean isImmersionBarEnabled();

    public void finish() {
        super.finish();
        hideSoftKeyBoard();
    }

    public void hideSoftKeyBoard() {
        View localView = getCurrentFocus();
        if (this.imm == null) {
            this.imm = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
        }
        if ((localView != null) && (this.imm != null)) {
            this.imm.hideSoftInputFromWindow(localView.getWindowToken(), 2);
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = getLayoutInflater().inflate(getLayoutId(), null);
        setContentView(view);

        mBottomNavigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
        mBottomNavigationBar.setTabSelectedListener(this);
        unbinder = ButterKnife.bind(this);
        ActivityUtils.addActivity(this);

        afterCreate(savedInstanceState);
        if (!RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().register(this);
        }
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
            view.setFitsSystemWindows(true);
        }
        //初始化沉浸式
        if (isImmersionBarEnabled())
            initImmersionBar();


    }


    /**
     * 添加 fragment 及 BottomNavigationItem（图标和文字）
     *
     * @param fragment    fragment
     * @param imageId     图标 ID
     * @param title       标题（String）
     * @param activeColor 选定时颜色
     */
    public void addItem(Fragment fragment, int imageId, String title, int activeColor) {
        fragmentList.add(fragment);
        mBottomNavigationBar
                .addItem(new BottomNavigationItem(imageId, title).setActiveColorResource(activeColor));
    }

    /**
     * 添加 fragment 及 BottomNavigationItem（图标和文字）
     *
     * @param fragment    fragment
     * @param imageId     图标 ID
     * @param title       标题（int）
     * @param activeColor 选定时颜色
     */
    public void addItem(Fragment fragment, int imageId, int title, int activeColor) {
        fragmentList.add(fragment);
        mBottomNavigationBar
                .addItem(new BottomNavigationItem(imageId, title).setActiveColorResource(activeColor));
    }

    /**
     * 添加 fragment 及 BottomNavigationItem（仅图标）
     *
     * @param fragment    fragment
     * @param imageId     图标 ID
     * @param activeColor 选定时颜色
     */
    public void addItem(Fragment fragment, int imageId, int activeColor) {
        fragmentList.add(fragment);
        mBottomNavigationBar
                .addItem(new BottomNavigationItem(imageId).setActiveColorResource(activeColor));
    }

    /**
     * 设置 BottomNavigationBar 风格样式
     *
     * @param mode            风格
     * @param backgroundStyle 背景样式
     */
    protected void setNavBarStyle(int mode, int backgroundStyle) {
        mMode = mode;
        mBackgroundStyle = backgroundStyle;
    }

    /**
     * 初始化容器，添加 fragment
     *
     * @param containerViewId 容器 ID
     */
    private int containerView;

    public void initialise(int containerViewId) {
        containerView = containerViewId;
        mBottomNavigationBar.setMode(mMode);
        mBottomNavigationBar.setBackgroundStyle(mBackgroundStyle);

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.layFrame, fragmentList.get(0));
        transaction.commit();

        mBottomNavigationBar.setFirstSelectedPosition(0).initialise();
    }


    @Override
    public void onTabSelected(int position) {
        if (fragmentList != null) {
            if (position < fragmentList.size()) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                //当前的fragment
                Fragment from = fm.findFragmentById(containerView);
                //点击即将跳转的fragment
                Fragment fragment = fragmentList.get(position);
                if (fragment.isAdded()) {
                    // 隐藏当前的fragment，显示下一个
                    ft.hide(from).show(fragment);
                } else {
                    // 隐藏当前的fragment，add下一个到Activity中
                    ft.hide(from).add(containerView, fragment);
                }
                ft.commitAllowingStateLoss();

            }
        }

    }

    @Override
    public void onTabUnselected(int position) {
        if (fragmentList != null) {
            if (position < fragmentList.size()) {
                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment fragment = fragmentList.get(position);
                // 隐藏当前的fragment
                ft.hide(fragment);
                ft.commitAllowingStateLoss();
            }
        }
    }

    @Override
    public void onTabReselected(int position) {

    }

    protected abstract int getLayoutId();

    protected abstract void afterCreate(Bundle savedInstanceState);

    /**
     * 申请权限
     *
     * @param permissions 需要申请的权限(数组)
     * @param listener    权限回调接口
     */
    public static void requestPermissions(String[] permissions, PermissionListener listener) {
        Activity activity = ActivityUtils.getTopActivity();
        if (null == activity) {
            return;
        }

        mPermissionListener = listener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            //权限没有授权
            if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(activity, permissionList.toArray(new String[permissionList.size()]), CODE_REQUEST_PERMISSION);
        } else {
            mPermissionListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case CODE_REQUEST_PERMISSION:
                if (grantResults.length > 0) {
                    List<String> deniedPermissions = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int result = grantResults[i];
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            String permission = permissions[i];
                            deniedPermissions.add(permission);
                        }
                    }

                    if (deniedPermissions.isEmpty()) {
                        mPermissionListener.onGranted();
                    } else {
                        mPermissionListener.onDenied(deniedPermissions);
                    }
                }
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
        ActivityUtils.removeActivity(this);
        if (RxBus.getDefault().isRegistered(this)) {
            RxBus.getDefault().unregister(this);
        }
        this.imm = null;
        if (mImmersionBar != null)
            mImmersionBar.destroy();  //在BaseActivity里销毁
    }
}